package com.example.license.client;

import com.example.model.Organization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component
@Slf4j
public class OrgDiscoveryClient implements Client{
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Organization getOrganization(int id) {
        // 获取服务实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("organization");
        if (instances.isEmpty()){
            return null;
        }
        // 拼接URL
        String url = instances.get(0).getUri().toString() + "/" + id;
        log.info("url: " + url);
        // 使用标准的 RestTemplate 调用远程服务
        Organization organization = restTemplate.getForObject(url, Organization.class);
        return organization;
    }
}
